<?php
// 开启会话
session_start();

// 初始化游戏数据
if (!isset($_SESSION['password'])) {
    // 生成一个 4 位的随机密码
    $_SESSION['password'] = str_pad(mt_rand(0, 9999), 4, '0', STR_PAD_LEFT);
    $_SESSION['attempts'] = 0;
    $_SESSION['max_attempts'] = 5;
}

// 处理用户提交的密码
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $user_input = $_POST["guess"];
    $_SESSION['attempts']++;

    if ($user_input === $_SESSION['password']) {
        $message = "恭喜你，解密成功！密码是：{$_SESSION['password']}";
        // 重置游戏
        unset($_SESSION['password']);
        unset($_SESSION['attempts']);
    } elseif ($_SESSION['attempts'] >= $_SESSION['max_attempts']) {
        $message = "很遗憾，你已用完所有尝试次数。正确密码是：{$_SESSION['password']}";
        // 重置游戏
        unset($_SESSION['password']);
        unset($_SESSION['attempts']);
    } else {
        $correct_digits = 0;
        for ($i = 0; $i < 4; $i++) {
            if ($user_input[$i] === $_SESSION['password'][$i]) {
                $correct_digits++;
            }
        }
        $message = "解密失败，你猜对了 {$correct_digits} 个数字。你还剩 " . ($_SESSION['max_attempts'] - $_SESSION['attempts']) . " 次尝试机会。";
    }
}
?>

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>解密游戏</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            background-color: #f4f4f9;
        }

        h1 {
            color: #333;
        }

        form {
            margin-top: 20px;
        }

        input[type="text"] {
            padding: 8px;
            font-size: 16px;
            width: 100px;
            text-align: center;
        }

        input[type="submit"] {
            padding: 8px 16px;
            font-size: 16px;
            background-color: #007BFF;
            color: white;
            border: none;
            cursor: pointer;
        }

        input[type="submit"]:hover {
            background-color: #0056b3;
        }

        #message {
            margin-top: 20px;
            color: green;
            font-size: 18px;
        }
    </style>
</head>

<body>
    <h1>解密游戏</h1>
    <p>请输入一个 4 位数字密码进行解密，你有 <?php echo isset($_SESSION['max_attempts']) ? $_SESSION['max_attempts'] : 5; ?> 次尝试机会。</p>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
        <input type="text" name="guess" pattern="[0-9]{4}" required placeholder="输入 4 位密码">
        <input type="submit" value="提交猜测">
    </form>
    <?php if (isset($message)): ?>
        <div id="message"><?php echo $message; ?></div>
    <?php endif; ?>
</body>

</html>